<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>退单管理 - EJ珠宝系统</title>
    <link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/bootstrap/icons/bootstrap-icons.css" rel="stylesheet">
    <link href="/static/css/ej.css" rel="stylesheet">
    <style>
        .return-table th {
            background-color: #f8f9fa;
            position: sticky;
            top: 0;
            font-weight: 600;
            font-size: 14px;
            padding: 12px 8px;
        }
        .return-table td {
            padding: 10px 8px;
            vertical-align: middle;
            font-size: 13px;
        }
        .table-responsive {
            max-height: 70vh;
            overflow-y: auto;
        }
        .btn-return {
            background-color: #dc3545;
            border-color: #dc3545;
        }
        .btn-return:hover {
            background-color: #c82333;
            border-color: #bd2130;
        }
        .return-form {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        /* 优化表格列宽 */
        .return-table th:nth-child(1), /* 销售ID */
        .return-table td:nth-child(1) {
            width: 80px;
            text-align: center;
        }
        
        .return-table th:nth-child(2), /* 销售时间 */
        .return-table td:nth-child(2) {
            width: 150px;
            text-align: center;
        }
        
        .return-table th:nth-child(3), /* 买家 */
        .return-table td:nth-child(3) {
            width: 100px;
            text-align: center;
        }
        
        .return-table th:nth-child(4), /* 库存编号 */
        .return-table td:nth-child(4) {
            width: 120px;
            text-align: center;
        }
        
        .return-table th:nth-child(5), /* 产品名称 */
        .return-table td:nth-child(5) {
            width: 180px;
            text-align: left;
        }
        
        .return-table th:nth-child(6), /* 产品图片 */
        .return-table td:nth-child(6) {
            width: 80px;
            text-align: center;
        }
        
        .return-table th:nth-child(7), /* 数量 */
        .return-table td:nth-child(7) {
            width: 70px;
            text-align: center;
        }
        
        .return-table th:nth-child(8), /* 销售金额 */
        .return-table td:nth-child(8) {
            width: 100px;
            text-align: right;
        }
        
        .return-table th:nth-child(9), /* 结算状态 */
        .return-table td:nth-child(9) {
            width: 90px;
            text-align: center;
        }
        
        .return-table th:nth-child(10), /* 操作 */
        .return-table td:nth-child(10) {
            width: 80px;
            text-align: center;
        }
        
        /* 美化表格行 */
        .return-table tbody tr:hover {
            background-color: #f8f9fa;
        }
        
        /* 美化操作按钮 */
        .return-table .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 12px;
        }
        
        /* 金额列样式 */
        .return-table td:nth-child(8) {
            font-weight: 500;
            color: #28a745;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div style="max-width: 1400px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">
                            <i class="bi bi-arrow-return-left"></i>
                            退单管理
                        </h5>
                    </div>
                    <div class="card-body">
                        <!-- 退单表单 -->
                        <div class="return-form">
                            <h6 class="text-primary mb-3">
                                <i class="bi bi-plus-circle"></i>
                                创建退单
                            </h6>
                            <form id="returnForm">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="stockId">库存编号 *</label>
                                            <input type="text" class="form-control" id="stockId" required>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="returnDate">退单日期 *</label>
                                            <input type="date" class="form-control" id="returnDate" required>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="returnQty">退单数量 *</label>
                                            <input type="number" class="form-control" id="returnQty" min="1" required>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label for="returnAmount">退单金额 *</label>
                                            <input type="number" class="form-control" id="returnAmount" step="0.01" min="0" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="returnReason">退单原因 *</label>
                                            <select class="form-control" id="returnReason" required>
                                                <option value="">请选择退单原因</option>
                                                <option value="质量问题">质量问题</option>
                                                <option value="客户取消">客户取消</option>
                                                <option value="库存调整">库存调整</option>
                                                <option value="其他原因">其他原因</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="comment">备注</label>
                                            <textarea class="form-control" id="comment" rows="1" placeholder="可选备注信息"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-3">
                                    <div class="col-12 text-end">
                                        <button type="submit" class="btn btn-return">
                                            <i class="bi bi-check-circle"></i>
                                            提交退单
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <!-- 可退单销售记录表格 -->
                        <div class="mt-4">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="text-primary mb-0">
                                    <i class="bi bi-list-check"></i>
                                    可退单销售记录
                                </h6>
                                <button class="btn btn-outline-primary btn-sm" onclick="loadSalesForReturn()">
                                    <i class="bi bi-arrow-repeat"></i>
                                    刷新列表
                                </button>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-striped table-hover return-table">
                                    <thead>
                                        <tr>
                                            <th>销售ID</th>
                                            <th>销售时间</th>
                                            <th>买家</th>
                                            <th>库存编号</th>
                                            <th>产品名称</th>
                                            <th>产品图片</th>
                                            <th>数量</th>
                                            <th>销售金额</th>
                                            <th>结算状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="salesTableBody">
                                        <tr>
                                            <td colspan="10" class="text-center text-muted">
                                                点击"刷新列表"加载可退单记录...
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载必要的JavaScript -->
    <script src="/static/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/common.js"></script>
    <script src="/static/js/ejj_functions.js"></script>
    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认退单日期为今天
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('returnDate').value = today;
            
            // 禁用产品ID点击功能（避免买家列有交互）
            if (typeof window.makeProductIdsClickable === 'function') {
                window.makeProductIdsClickable = function() {
                    console.log('退单管理页面已禁用产品ID点击功能');
                    // 什么都不做，保持所有列为普通文本
                };
            }
            
            // 加载可退单销售记录
            loadSalesForReturn();
        });

        // 加载可退单销售记录
        function loadSalesForReturn() {
            const tableBody = document.getElementById('salesTableBody');
            tableBody.innerHTML = '<tr><td colspan="10" class="text-center text-muted">正在加载...</td></tr>';

            fetch('/get_sales_for_return', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.data.length === 0) {
                        tableBody.innerHTML = '<tr><td colspan="10" class="text-center text-muted">没有可退单的销售记录</td></tr>';
                        return;
                    }

                        tableBody.innerHTML = '';
                        data.data.forEach(sale => {
                            const row = document.createElement('tr');
                            
                            // 生成产品图片HTML
                            const productImageHtml = sale.product_id ? 
                                `<img src="/serve_jade_image?product_id=${sale.product_id}" 
                                      alt="${sale.product_id}" 
                                      style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px; cursor: pointer;"
                                      onerror="this.src='/static/images/default_cover.jpg'"
                                      onclick="showJadeImages('${sale.product_id}')"
                                      title="点击查看产品图片">` : 
                                '<span style="color: #999; font-size: 12px;">无图片</span>';
                            
                            row.innerHTML = `
                                <td>${sale.id}</td>
                                <td>${new Date(sale.sale_datetime).toLocaleString()}</td>
                                <td>${sale.buyer_name || '-'}</td>
                                <td>${sale.stock_id}</td>
                                <td>${sale.product_name || '-'}</td>
                                <td style="text-align: center;">${productImageHtml}</td>
                                <td>${sale.sale_qty}</td>
                                <td>¥${parseFloat(sale.sale_real_price || 0).toFixed(2)}</td>
                                <td>
                                    <span class="badge ${getSettlementBadgeClass(sale.settlement_status)}">
                                        ${getSettlementStatusText(sale.settlement_status)}
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" 
                                            onclick="fillReturnForm('${sale.stock_id}', ${sale.sale_qty}, ${sale.sale_real_price || 0}, '${sale.product_id || ''}')">
                                        <i class="bi bi-arrow-left-circle"></i>
                                        选择
                                    </button>
                                </td>
                            `;
                            tableBody.appendChild(row);
                        });
                } else {
                    tableBody.innerHTML = `<tr><td colspan="10" class="text-center text-danger">${data.message}</td></tr>`;
                }
            })
            .catch(error => {
                tableBody.innerHTML = '<tr><td colspan="10" class="text-center text-danger">加载失败</td></tr>';
                console.error('Error:', error);
            });
        }

        // 根据结算状态获取badge样式
        function getSettlementBadgeClass(status) {
            switch (status) {
                case 'completed': return 'bg-success';
                case 'partial': return 'bg-warning';
                case 'pending': return 'bg-secondary';
                default: return 'bg-secondary';
            }
        }

        // 根据结算状态获取显示文本
        function getSettlementStatusText(status) {
            switch (status) {
                case 'completed': return '已结算';
                case 'partial': return '部分结算';
                case 'pending': return '未结算';
                default: return status;
            }
        }

        // 使用系统中已有的showJadeImages函数（在ejj_functions.js中定义）
        // 该函数会显示产品所有图片的完整浏览界面
        // 包括缩略图导航、键盘导航等功能

        // 填充退单表单
        function fillReturnForm(stockId, qty, amount, productId) {
            document.getElementById('stockId').value = stockId;
            document.getElementById('returnQty').value = qty;
            document.getElementById('returnAmount').value = amount.toFixed(2);
            
            if (productId) {
                // 如果有产品ID，可以在这里进行其他操作
            }
            
            // 滚动到表单位置
            document.getElementById('returnForm').scrollIntoView({
                behavior: 'smooth'
            });
        }

        // 处理退单表单提交
        document.getElementById('returnForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = {
                stock_id: document.getElementById('stockId').value,
                return_date: document.getElementById('returnDate').value,
                return_reason: document.getElementById('returnReason').value,
                return_qty: parseFloat(document.getElementById('returnQty').value),
                return_amount: parseFloat(document.getElementById('returnAmount').value),
                comment: document.getElementById('comment').value,
                product_id: '' // 可以从选择的数据中获取
            };

            // 表单验证
            if (!formData.stock_id || !formData.return_date || !formData.return_reason || 
                !formData.return_qty || !formData.return_amount) {
                alert('请填写所有必填字段');
                return;
            }

            if (formData.return_qty <= 0 || formData.return_amount <= 0) {
                alert('退单数量和金额必须大于0');
                return;
            }

            // 显示加载中
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 处理中...';
            submitBtn.disabled = true;

            // 发送退单请求
            fetch('/create_return', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;

                if (data.success) {
                    alert(`退单创建成功！退单编号: ${data.return_id}`);
                    // 清空表单
                    document.getElementById('returnForm').reset();
                    document.getElementById('returnDate').value = new Date().toISOString().split('T')[0];
                    // 重新加载销售记录
                    loadSalesForReturn();
                } else {
                    alert(`退单创建失败: ${data.message}`);
                }
            })
            .catch(error => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
                alert('网络错误，请重试');
                console.error('Error:', error);
            });
        });
    </script>
</body>
</html>
